const {util: {getPos}} = require('../util')
import javaConnector from "@/plugins/javaConnector";

export default (Vue) => {
  /**
   * 移动窗口位置
   */
  Vue.directive('drag-window', {
    // 当被绑定的元素插入到 DOM 中时……
    bind(el, binding, vnode, oldVnode) {
      el.onmousedown = function (e) {

        let mouseLocation = javaConnector.getMouseLocation();
        mouseLocation = JSON.parse(mouseLocation)

        let location = javaConnector.getLocation();
        location = JSON.parse(location)

        let screenX = e.screenX
        let screenY = e.screenY
        document.onmousemove = function (ev) {

          let mouseLocation = javaConnector.getMouseLocation();
          mouseLocation = JSON.parse(mouseLocation)

          let newX = location.x + ev.screenX - screenX
          let newY = location.y + ev.screenY - screenY

          console.log("x：" + newX)
          console.log("y：" + newY)
          javaConnector.setLocation(newX, newY)
        }
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null
        }
      }
    }
  })

  /**
   * 拖拽
   */
  Vue.directive('drag', {
    // 当被绑定的元素插入到 DOM 中时……
    bind(el, binding, vnode, oldVnode) {
      el.onmousedown = function (e) {
        let sP = getPos(el, el.parentElement)
        let mP = {
          x: e.screenX,
          y: e.screenY
        }
        document.onmousemove = function (ev) {
          let x = sP.x + ev.screenX - mP.x
          let y = sP.y + ev.screenY - mP.y
          if (x < 0) x = 0
          if (y < 40) y = 40
          if (x > sP.width - el.offsetWidth) x = sP.width - el.offsetWidth
          if (y > sP.height - el.offsetHeight) y = sP.height - el.offsetHeight
          el.style.left = x + 'px'
          el.style.top = y + 'px'
        }
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null
        }
      }
    }
  })

  /**
   * 焦点
   */
  Vue.directive('focus', {
    bind: function (el, binding, vnode) {
      if (binding.value) {
        setTimeout(() => {
          el.focus()
        }, 0)
      }
    }
  })
}
